/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { message } from "antd";
import { getCostList, giveCostOut, costSetting, getSingleCost } from "@/services/delivery";

export default {
  namespace: "cost",
  state: {
    costList: {},
    singleCost:null
  },

  effects: {
    * getCostList({ payload }, { call, put, select }) {
      const { code, data } = yield call(getCostList, payload);
      if (code == 0) {
        yield put({
          type: "save",
          payload: {
            costList: {
              list: data.list,
              pagination: {
                total: parseInt(data.count),
                pageSize: data.size || 10
              }
            }
          }
        });
      }
    },
    * giveCostOut({ payload, callback }, { call }) {
      const { code, msg } = yield call(giveCostOut, payload);
      if (code == 0) {
        callback();
        message.success("已发放");
      } else {
        message.error(msg);
      }
    },
    * costSetting({ payload, callback }, { call, put }) {
      const { code, msg } = yield call(costSetting, payload);
      if (code == 0) {
        yield put({
          type: "save",
          payload: {
            singleCost: payload
          }
        });
        message.success("设置成功");
        callback();
      } else {
        message.error(msg);
      }
    },
    * getSingleCost({ payload }, { call, put, select }) {
      let {
        singleCost
      } = yield select(_ => _.cost);
      if(singleCost) return;
      const { code, data } = yield call(getSingleCost);
      if (code == 0) {
        yield put({
          type: "save",
          payload: {
            singleCost: data.length > 0 ? data[0] : null
          }
        });
      }
    }
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload
      };
    }
  }
};
